package com.example.novelweb.utils.WordCheck;

import cn.hutool.core.collection.CollUtil;

import java.util.*;



public class WordCheckUtil {
  private static final DfaTree dfaTree = new DfaTree();

  public static void addWords(String... words) {
    dfaTree.addWords(words);
  }

  public static void addWords(Collection<String> words) {
    dfaTree.addWords(words);
  }

  public static void delWords(String... words) {
    dfaTree.addWords(words);
  }

  public static void delWords(Collection<String> words) {
    dfaTree.addWords(words);
  }

  public static String findWordsAndReplace(String text) {
    List<FoundResult> results = dfaTree.findWords(text);
    if (results == null || results.isEmpty()) {
      // 不需要处理
      return null;
    }

    StringBuilder sb = new StringBuilder(text);

//    results.sort((r1, r2) -> Integer.compare(r1.getOff(), r2.getOff()));

    // 从后往前遍历替换结果，避免影响尚未处理的偏移
    for (int i = results.size() - 1; i >= 0; i--) {
      FoundResult r = results.get(i);

      sb.replace(r.getOff(), r.getOff() + r.getLen(),StrRepeat('*',r.getLen()));
    }

    // 将修改后的 StringBuilder 转为字符串并返回
    return sb.toString();
  }

  private static String StrRepeat(char c, int len) {
    StringBuilder sb = new StringBuilder(len);
    for(int i=0;i<len;++i) {
      sb.append(c);
    }
    return sb.toString();
  }


}



